package com.hyg.module_report.ui.activity;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.animation.ArgbEvaluator;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.hyg.lib_base.MyView.AutoHeightViewPager;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.module_report.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;


public class InsertReportActivity extends BaseActivity implements View.OnClickListener{

    TextView tv_text1; // 标签栏中的页面1标签
    TextView tv_text2; // 标签栏中的页面2标签
    TextView tv_line1, tv_line2; // 标签栏中的页面3标签
    View view1;// 在页面1里的所有视图控件的调用需要使用的前缀
    View view2;// 在页面2里的所有视图控件的调用需要使用的前缀
    private List<TextView> textList; // 文字集合
    AutoHeightViewPager mViewPager;
    private Button bt_ok,bt_sure;
    private ImageView back;
    private TextView timertext ;
    private Timer mTimer = null;
    private EditText et_code,et_phone,et_pass,et_smscode;
    private ToggleButton togglePwd;
    private Button getcode;
    private String code="";
    private String phone="";
    private String password="";
    public String mphone = "[1][3456789]\\d{9}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mcode = "\\d{4,6}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mpassword = "[A-Za-z0-9]{6,18}";//第一位是字母，后面加上4-15个


    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private InsertReportActivity activity;
        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (InsertReportActivity) reference.get();
        }
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://用查询手机号自己的所有报告
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                        Log.d("welcomeInsertReport", jsondata+"");
                        if (status.equals("200")) {
                            activity.editorn = activity.sn.edit();
                            activity.editorn.putString("InsertReport","1");
                            activity.editorn.commit();
                            activity.dialogShow();

                        } else {
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
                case 2://获取注册验证码
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String success = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadLogin", jsondata+"");
                        if (success.equals("200")){
                            Toast.makeText(activity,message, Toast.LENGTH_SHORT).show();
                        } else {
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;

                case 100:
                    activity.getcode.setText(activity.countdown + "s后可获取");
                    activity.getcode.setAlpha(0.5f);
                    if (0 == activity.countdown) {
                        //停止倒计时显示页面
                        activity.resume();
                        activity.stopmTimer();
                        return;
                    }
                    activity.countdown--;
                    break;
                case 101://对话框倒计时，结束直接退出
                    activity.timertext.setText(activity.countdown3 + "");
                    if (0 == activity.countdown3) {
                        activity.stopTimer();
                        if (activity.pDialog.isShowing()) {
                            activity.pDialog.dismiss();
                        }
                        activity.countdown3--;
                        //停止倒计时显示页面
                        activity.finish();
                        activity.overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
                        return;
                    }
                    if (activity.pDialog.isShowing()) {
                        activity.countdown3--;
                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_report);
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.white),00,null,null,true);
        init();

    }
    Timer timer = new Timer();

    public void dialogShow(){
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(InsertReportActivity.this);
        View view = inflater.inflate(R.layout.dialog_layouts, null);
        timertext = view.findViewById(R.id.tv_dialog);
        timertext.setGravity(Gravity.CENTER);
        TimerTask timerTask = new TimerTask() {
            public void run() {
                myHandler.sendEmptyMessage(101);
            }
        };
        countdown3 = 3;
        if (pDialog.isShowing()) {
            pDialog.cancel();
        }
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
        pDialog.setTitleText("已成功绑定该手机号的全部报告，3秒后自动跳转到报告列表");
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("立即前往", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                stopmTimer();
                pDialog.dismiss();
                InsertReportActivity.this.finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });
        pDialog.setCancelButton("留在本页", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                timer.cancel();
                sweetAlertDialog.dismiss();
            }
        });
        pDialog.show();
        timer.schedule(timerTask,500,1000);
    }

    public void init(){

        tv_text1 = (TextView) findViewById(R.id.text1);
        tv_text2 = (TextView) findViewById(R.id.text2);
        tv_line1 = (TextView) findViewById(R.id.line1);
        tv_line2 = (TextView) findViewById(R.id.line2);
        mViewPager = (AutoHeightViewPager) findViewById(R.id.viewFlipper1);// 定义页面设置成带有动画和滑动效果的mViewpager对象
        List<View> mList = new ArrayList<View>(); // 创建一个List，用于存放4个页面
        //		iconList = new ArrayList<ImageView>();
        textList = new ArrayList<TextView>();
        textList.add(tv_text1);
        textList.add(tv_text2);

        LayoutInflater inflater = LayoutInflater.from(this);// 调用LayoutInflater类
        view1 = inflater.inflate(R.layout.insert_report_phone, null);
        view2 = inflater.inflate(R.layout.insert_report_smscode, null); // 定义view2对象，与R.layout.view2页面关联
        mList.add(view1);
//        mList.add(view2);
        MyPagerAdapter adapter = new MyPagerAdapter(mList);
        mViewPager.setAdapter(adapter); // 将adapter设置为mViewPager的adapter
        mViewPager.setOnPageChangeListener(adapter); // 使mViewPager响应OnChangeListener事件
        tv_text1.setOnClickListener(this); // 设置页面1标签的点击事件
        tv_text2.setOnClickListener(this); // 设置页面2标签的点击事件

        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {if(Utils.isFastClick()){return ;}
                InsertReportActivity.this.finish();
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
        initPhone();
        initPass();
    }

    public void initPhone(){
        bt_ok = (Button)view1.findViewById(R.id.Insert);
        getcode = (Button)view1.findViewById(R.id.getcode);
        et_code = (EditText)view1.findViewById(R.id.et_code);
        et_phone = (EditText)view1.findViewById(R.id.userphone);

        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                phone = et_phone.getText().toString();
                code = et_code.getText().toString();
                AutoInsertPhone(phone,code);
            }
        });

        getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_phone.getText().toString();
                if (Utils.isFastClick()) {
                    return;
                }
                countdown = 45;
                if (phone.equals("")) {
                    Toast.makeText(InsertReportActivity.this, "电话号码不可为空，请填写电话号码。", Toast.LENGTH_SHORT).show();
                } else if (!phone.matches(mphone)) {
                    Toast.makeText(InsertReportActivity.this, "电话号码格式不对，请重新输入。", Toast.LENGTH_SHORT).show();
                    et_phone.setText("");
                } else {
                    et_code.setHint("请注意查看短信");
                    startTimer();
                    String str_tag = "2";
                    FormBody formBody = new FormBody.Builder()
                            .add("phone", phone)//设置参数名称和参数值
                            .build();
                    sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.codeaddr);
                }
            }
        });
    }

    public void AutoInsertPhone(String phone,String code){

        if (phone.equals("")) {
            Toast.makeText(InsertReportActivity.this, "请填写手机号。", Toast.LENGTH_SHORT).show();
        }else if(code.equals("")){
            Toast.makeText(InsertReportActivity.this, "请填写验证码。", Toast.LENGTH_SHORT).show();
        }else {
            if (!phone.matches(mphone)) {
                Toast.makeText(InsertReportActivity.this, "手机号格式错误，请重新输入。", Toast.LENGTH_SHORT).show();
            }else if (!code.matches(mcode)) {
                Toast.makeText(InsertReportActivity.this, "验证码格式错误，请重新输入。", Toast.LENGTH_SHORT).show();
            }  else {

                {
                    String str_tag = "1";
//                    String data = "paraPhone=" + phone + "&smsCode=" + code + "&token=" + sn.getString("token", "");
                    FormBody formBody = new FormBody.Builder()
                            .add("paraPhone", phone)//设置参数名称和参数值
                            .add("smsCode", code)//设置参数名称和参数值
                            .add("token", sn.getString("token", ""))//设置参数名称和参数值
                            .build();
                    sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.bindByPhoneddr);
                }
            }
        }
    }


    public void initPass(){
        bt_sure = (Button)view2.findViewById(R.id.Insert);
        et_pass = (EditText)view2.findViewById(R.id.password);
        et_smscode = (EditText)view2.findViewById(R.id.smscode);
        togglePwd = (ToggleButton) view2.findViewById(R.id.togglePwd);

        togglePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) { //如果选中，显示密码
                    et_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else { //否则隐藏密码
                    et_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });

        bt_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                phone = et_smscode.getText().toString();
                password = et_pass.getText().toString();
                AutoLoginPassword(phone,password);
            }
        });

    }

    public void AutoLoginPassword(String username,String password){

        if (username.equals("")) {
            Toast.makeText(InsertReportActivity.this, "请填写体检编号。", Toast.LENGTH_SHORT).show();
        } else if (password.equals("")) {
            Toast.makeText(InsertReportActivity.this, "密码不可为空，请填写密码。", Toast.LENGTH_SHORT).show();
        } else {
            if (!username.matches(mphone)) {
                Toast.makeText(InsertReportActivity.this, "体检编号格式错误，请重新输入。", Toast.LENGTH_SHORT).show();
                et_smscode.setText("");
            } else if (!password.matches(mpassword)) {
                Toast.makeText(InsertReportActivity.this, "密码格式不对或者包含非格式字符，请重新输入。", Toast.LENGTH_SHORT).show();
                et_pass.setText("");
            } else {

                {
                    String str_tag = "1";
//                    String data = "barcode=" + username + "&pwd=" + password + "&token=" + sn.getString("token", "");
                    FormBody formBody = new FormBody.Builder()
                            .add("barcode", username)//设置参数名称和参数值
                            .add("pwd", password)//设置参数名称和参数值
                            .add("token", sn.getString("token", ""))//设置参数名称和参数值
                            .build();
                    sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.codeaddr);
                }
            }
        }

    }

    class MyPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {
        // PagerAdapter主要是viewpager的适配器，而viewPager则也是在android.support.v4扩展包中新添加的一个强大的控件，可以实现控件的滑动效果，比如咱们在软件中常见的广告栏的滑动效果，用viewPager就可以实现
        private List<View> mList;

        // 构造函数，接收List参数，以便对其中的元素（页面）进行操作
        public MyPagerAdapter(List<View> views) {
            mList = views;
        }

        // 返回页面的数量
        @Override
        public int getCount() {// 获取要滑动的控件的数量
            return mList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {// 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) { // PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
            container.removeView(mList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {// 当要显示的图片可以进行缓存的时候，会调用这个方法进行显示图片的初始化，我们将要显示的ImageView加入到ViewGroup中，然后作为返回值返回即可
            container.addView(mList.get(position), 0);
            return mList.get(position);
        }

        // 此方法和下面的onPageScrolled方法是实现OnPageChangeListener接口必须覆盖的方法
        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            ArgbEvaluator evaluator = new ArgbEvaluator(); // ARGB求值器
            int evaluate = 0x00FFFFFF; // 初始默认颜色（透明白）
            int evaluate2 = 0X00FFFFFF;
            int evaluate3 = 0X00FFFFFF;
            int evaluate4 = 0X00FFFFFF;
            if (position == 0) {
                evaluate = (Integer) evaluator.evaluate(positionOffset, 0XFF7b40be, 0XFF333333); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                evaluate2 = (Integer) evaluator.evaluate(positionOffset, 0XFF333333, 0XFF7b40be); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                evaluate3 = (Integer) evaluator.evaluate(positionOffset, 0XFF7b40be, 0XFFFFFFFF); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                evaluate4 = (Integer) evaluator.evaluate(positionOffset, 0XFFFFFFFF, 0XFF7b40be); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                tv_text1.setTextColor(evaluate);
                tv_line1.setBackgroundColor(evaluate3);
                tv_text2.setTextColor(evaluate2);
                tv_line2.setBackgroundColor(evaluate4);
//                Log.d("offset", positionOffset + "\n");
            } else if (position == 1) {
                //					evaluate = (Integer) evaluator.evaluate(positionOffset, 0XFF3190e8, 0XFF000000); // 根据positionOffset和第1页~第2页的颜色转换范围取颜色值
                //					tv_text1.setTextColor(evaluate2);
                //					tv_line1.setBackgroundColor(evaluate2);
                //					tv_text2.setTextColor(evaluate);
                //					tv_line2.setBackgroundColor(evaluate3);
            } else if (position == 2) {
                //					evaluate = (Integer) evaluator.evaluate(positionOffset, 0XFF199AFE, 0XFF00AB96); // 根据positionOffset和第2页~第3页的颜色转换范围取颜色值
            } else {
                evaluate = 0XFF00AB96; // 最终第3页的颜色
            }

            //				((View)mViewPager.getParent()).setBackgroundColor(evaluate); // 为ViewPager的父容器设置背景色 }
        }

        // 当page被选择的时候，将此页标签上的文字设置为白色，其他标签上的文字设置为黑色，position从0开始
        @Override
        public void onPageSelected(int position) {
            //			String[] biaoqian = new String[] { "预约会议", "会务情况","我的预约", "会议审批" ,"会服处理"};
            //				curIndex = position;

            switch (position) {
                case 0:// 将页面1设置成白色
                    tv_text1.setTextColor(getResources().getColor(R.color.MainThemeColor));
                    tv_text2.setTextColor(Color.rgb(0, 0, 0));
                    tv_line1.setBackgroundColor(getResources().getColor(R.color.MainThemeColor));
                    tv_line2.setBackgroundColor(Color.rgb(255, 255, 255));

                    break;
                case 1:// 将页面2设置成白色
                    tv_text1.setTextColor(Color.rgb(0, 0, 0));
                    tv_text2.setTextColor(getResources().getColor(R.color.MainThemeColor));
                    tv_line1.setBackgroundColor(Color.rgb(255, 255, 255));
                    tv_line2.setBackgroundColor(getResources().getColor(R.color.MainThemeColor));
                    break;
            }
        }

    }

    // 标签文字的点击事件，通过识别点击的TextView，设置mViewPager显示的页面
    @Override
    public void onClick(View v) {
        if (Utils.isFastClick()) {
            return;
        }
        int index = 0;
        int id = v.getId();
        if (id == R.id.text1) {
            index = 0;
        } else if (id == R.id.text2) {
            index = 1;
        }
        mViewPager.setCurrentItem(index); // 设置当前显示的页面
    }

    //开始倒计时
    private void startTimer() {
        //点击获取验证码后改变按钮的状态,让按钮不可点击
        getcode.setClickable(false);
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {

                myHandler.sendEmptyMessage(100);
            }
        }, 0, 1000);
    }

    private int countdown = 60;
    private int countdown3 = 3;

    private void resume() {
        stopmTimer();
        //倒计时结束后,让按钮重新可点击
        getcode.setClickable(true);
        getcode.setText("获取验证码");
        getcode.setAlpha(0.9f);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void stopmTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    //改写返回键功能
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            InsertReportActivity.this.finish();

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}
